//
//  PriceView.m
//  car
//
//  Created by chenxu on 4/7/15.
//  Copyright (c) 2015 chenxu. All rights reserved.
//

#import "PriceView.h"
#import "price_cell.h"
#import "price_cell_company.h"
#import "NetAPIManager.h"
#import "Insurance.h"
#import "ODRefreshControl.h"
#define kCellIdentifier_price @"price_cell"
#define kCellIdentifier_price_company @"price_cell_company"
#define kCellIdentifier_price_companytotal @"price_cell_companytotal"

#define kCellIdentifier_title @"title_cell"

@interface PriceView()

@property (nonatomic,strong) UITableView* myTableView;
@property (nonatomic, strong) ODRefreshControl *refreshControl;
@property (nonatomic,strong) Order* myOrder;
@property (nonatomic,strong) NSMutableArray* array;
@property (nonatomic , copy) cancelOrder cancelblock;
@property (nonatomic , copy) acceptOrder acceptblock;
@property (nonatomic , copy) sendOrder sendblock;
@property (nonatomic , copy) selectcar selectblock;

@end

@implementation PriceView

//用户
- (id)initWithFrame:(CGRect)frame andOrder:(Order*)order cancel:(cancelOrder)cancelblock accept:(acceptOrder)acceptblock selectcar:(selectcar)selectblock{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        _who = user;
        _isshow = false;
        _myOrder = order;
        _cancelblock = cancelblock;
        _acceptblock = acceptblock;
        _selectblock = selectblock;
        
        _myTableView = ({
            UITableView *tableView = [[UITableView alloc] initWithFrame:self.bounds style:UITableViewStyleGrouped];
            tableView.backgroundColor = kColorTableBG;
            tableView.delegate = self;
            tableView.dataSource = self;
            [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kCellIdentifier_title];
            [tableView registerClass:[price_cell class] forCellReuseIdentifier:kCellIdentifier_price];
            tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
            [self addSubview:tableView];
            tableView;
        });
        _myTableView.tableFooterView = [self tableFooterView];
        [self refreshPrice];
        [self setY:-700];
        
        _refreshControl = [[ODRefreshControl alloc] initInScrollView:self.myTableView];
        [_refreshControl addTarget:self action:@selector(refreshPrice) forControlEvents:UIControlEventValueChanged];
    }
    
    return self;
    
}

//商家
- (id)initWithFrame:(CGRect)frame andOrder:(Order*)order send:(sendOrder)sendblock selectcar:(selectcar)selectblock{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        _who = company;
        _isshow = false;
        _myOrder = order;
        _sendblock = sendblock;
        _selectblock = selectblock;
        
        _myTableView = ({
            UITableView *tableView = [[UITableView alloc] initWithFrame:self.bounds style:UITableViewStyleGrouped];
            tableView.backgroundColor = kColorTableBG;
            tableView.delegate = self;
            tableView.dataSource = self;
            [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kCellIdentifier_title];
            [tableView registerClass:[price_cell_company class] forCellReuseIdentifier:kCellIdentifier_price_company];
            [tableView registerClass:[price_cell_company class] forCellReuseIdentifier:kCellIdentifier_price_companytotal];

            tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
            [self addSubview:tableView];
            tableView;
        });
        _myTableView.tableFooterView = [self tableFooterView];
        
        _refreshControl = [[ODRefreshControl alloc] initInScrollView:self.myTableView];
        [_refreshControl addTarget:self action:@selector(refreshPrice) forControlEvents:UIControlEventValueChanged];

        
        [self refreshPrice];
        [self setY:-700];
    }
    
    return self;
}
- (void)refreshPrice{
    __weak typeof(self) weakSelf = self;
    [weakSelf.refreshControl beginRefreshing];

    //从服务器刷新报价
    [[NetAPIManager sharedManager]refresh_price:[_myOrder toRefreshParams] andBlock:^(id data, NSError *error) {
        if (data) {
            [weakSelf.refreshControl endRefreshing];
            weakSelf.array = [[NSMutableArray alloc]initWithArray:data];
            
            [weakSelf.myTableView reloadData];
        }
        
    }];
}

#pragma mark - table view
#pragma mark Table Data Source Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 2) {
        if (_array) {
            return _array.count+1;
        }
        else{
            return 0;
        }
    }
    else{//section = 0,1
        return 1;
    }
}

#pragma mark Table Delegate Methods

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
            if (indexPath.section == 0) {
                UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_title forIndexPath:indexPath];
                cell.imageView.image = [UIImage imageNamed:@"sjbj"];
                cell.textLabel.text = _myOrder.Carid;
                cell.textLabel.textColor = kColorTheme;
                
                return  cell;
            }
            if (indexPath.section == 1) {
                UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_title forIndexPath:indexPath];
                cell.textLabel.text = _myOrder.Company;
                cell.textLabel.textColor = kColorTheme;
                
                return  cell;
            }
            else{
                switch (_who) {
                    case company:
                    {
                        if (indexPath.row < _array.count) {
                            price_cell_company* cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_price_company forIndexPath:indexPath];
                            Insurance* ins = [_array objectAtIndex:indexPath.row];
                            
                            [cell setLeft:ins.xianming right:ins.price cellType:com_price_normal];
                            cell.endEdit = ^(NSString* price){
                                ins.price = price;
                                [tableView reloadData];
                            };
                            cell.onEdit = ^(NSString* price){
                                ins.price = price;
                            };
                            return cell;
                        }
                        else{
                            price_cell_company* cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_price_companytotal forIndexPath:indexPath];
                            [cell setLeft:@"共计" right:[self getsum] cellType:com_price_total];
                            return cell;
                        }
                    }
                        break;
                    
                        
                    case user:
                    {
                        if (indexPath.row < _array.count) {
                            price_cell* cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_price forIndexPath:indexPath];
                            Insurance* ins = [_array objectAtIndex:indexPath.row];
                            [cell setLeft:ins.xianming right:ins.price cellType:price_normal];
                            return cell;
                        }
                        else{
                            price_cell* cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_price forIndexPath:indexPath];
                            [cell setLeft:@"共计" right:[self getsum] cellType:price_total];
                            return cell;
                        }
                    }
                        break;
                    default:
                        break;
                }
                

            }
    
   
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0 && indexPath.row == 0) {
        if (_selectblock) {
            _selectblock();
        }
    }
}

- (NSString*)getsum{
    NSInteger ret = 0;
    for (int i=0; i<_array.count; i++) {
        Insurance* ins = [_array objectAtIndex:i];
        ret += [ins.price integerValue];
    }
    NSString* str = [NSString stringWithFormat:@"%ld",(long)ret];
    return str;
}


- (UIView*)tableFooterView{
    
    UIView *footerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 70)];

    switch (_who) {
        case user:{
            UIButton *cancelBtn = [UIButton buttonWithStyle:StrapWarningStyle andTitle:@"取消订单" andFrame:CGRectMake(40, 0, 100, 40) target:self action:@selector(cancel)];
            UIButton *acceptBtn = [UIButton buttonWithStyle:StrapSuccessStyle andTitle:@"接收报价" andFrame:CGRectMake(kScreen_Width - 140, 0, 100, 40) target:self action:@selector(accept)];
            
            [cancelBtn setPopingPressed];
            [acceptBtn setPopingPressed];
            
            [footerV addSubview:cancelBtn];
            [footerV addSubview:acceptBtn];
            break;
        }
            
        case company:{
            UIButton *acceptBtn = [UIButton buttonWithStyle:StrapSuccessStyle andTitle:@"发送报价" andFrame:CGRectMake(140, 0, 100, 40) target:self action:@selector(send)];
            
            [acceptBtn setPopingPressed];
            [acceptBtn setCenter:footerV.center];
            [footerV addSubview:acceptBtn];
            break;
        }
    }
    
    
    return footerV;
}


//取消订单按钮
- (void)selectcar{
    if (_selectblock) {
        _selectblock();
    }
}


//取消订单按钮
- (void)cancel{
    if (_cancelblock) {
        _cancelblock();
        
        [[NetAPIManager sharedManager]delete_order:[_myOrder toOrderidParams] andBlock:^(id data, NSError *error) {
            
        }];
    }
}

//接收报价按钮
- (void)accept{
    if (_acceptblock) {
        _acceptblock(_array);
    }
}

- (void)send{
    if (_sendblock) {
        _sendblock(_array);
        NSDictionary* param  = @{
                                 @"Orderid" : _myOrder.Orderid,
                                 @"Xianzhong" : [self tojsonString]
                                 };
        [[NetAPIManager sharedManager]company_baojia:param andBlock:^(id data, NSError *error) {
            if (data) {
                [self showHudTipStr:@"发送成功"];
            }
        }];
    }
}

- (void)showOrDismiss{
    //显示
    if (_isshow == false) {
        _isshow = true;
        [UIView animateWithDuration:0.1 delay:0.0 options:UIViewAnimationOptionTransitionFlipFromTop animations:^{
            [self setY:0 ];
            
        }completion:^(BOOL finished) {
            
        }];
    }
    //隐藏
    else{
        _isshow = false;
        if ([self isFirstResponder]) {
            [self resignFirstResponder];
        }
        [UIView animateWithDuration:0.25 delay:0.0 options:UIViewAnimationOptionTransitionFlipFromTop animations:^{
            [self setY:-700];
            
        } completion:^(BOOL finished) {
            
            //[self removeFromSuperview];
        }];
    }
}

- (NSString* )tojsonString{
    NSMutableString* ret = [[NSMutableString alloc]init];
    [ret appendString:@"["];
    
    
    for (int i = 0; i< [_array count]; i++) {
        Insurance * ins = [_array objectAtIndex:i];
        NSDictionary* unit = @{
                               @"xianming" : ins.xianming,
                               @"price"    : ins.price
                               };
        NSString* json = [unit JSONString];
    
        [ret appendString:json];
        if (i != [_array count]) {
            [ret appendString:@","];
        }
        else{
            [ret appendString:@"]"];
        }
    }
    return ret;
    
}

@end
